let host = getServiceHostAndPort();
let searchInfoURL = host+"/api/v3/enterprise/details?creditCode=";
let getUserInfo = host+"/api/v3/getUserInfo";
let searchListURL = host+"/api/v3/enterprise/search"
let hoardURL = host+"/api/v3/enterprise/hoard";
let shades = ["shade-primary", "shade-secondary", "shade-green", "shade-red", "shade-yellow", "shade-blue", "shade-dark"];

let searchListData = {
    "keyword": "",
    "page": 1,
    "perPage": 10
}


$(function () {
    searchCompanyInfo('91110106722616456B',true)
    keyMoreThan2();
    $('#search-btn').click(function () {
        searchCompanyList();
    });

    $('#hoard').click(function(){
        hoard();
    });

    $(document).click(function (e) {
        if (!$(e.target).is('#search-btn')) {
            $('#companyNameList').hide();
        }
    });
});


$(function () {
    $.getJSON(getUserInfo, null, function (result){
     document.getElementById('sName').innerHTML = result.userName;
    });
});


function searchCompanyList() {
    let searchData = $('#search-data').val();

    if ($.trim(searchData) === "") {
        alert("查询条件不可为空");
        return;
    }

    searchListData.keyword = searchData;


    $.ajax({
        url: searchListURL,
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(searchListData),
        success: function(result) {
            searchCompanyListCallback(result)
        },
        error: function(xhr, status, error) {
            console.error('请求失败:', error);
        }
    });
}

function searchCompanyListCallback(result) {
    let data = result.rows.data
    addCompanyAccordion(data);
}


function searchCompanyInfo(creditCode,hideName) {
    $.getJSON(searchInfoURL + creditCode, null, function (result){
        searchCompanyInfoCallback(result,hideName)
    });
}

function searchCompanyInfoCallback(result,hideName) {
    let data = result.rows;
    if(!hideName){
        $('#search-data').val(data.name);
    }
    $('#company-name').text(data.name);
    $('#legalPersonName').text(empty2MinusSign(data.legalPersonName));//法定代表人

    let estiblishTime = data.estiblishTime;
    estiblishTime = estiblishTime.split(' ')[0];
    $('#estiblishTime').text(empty2MinusSign(estiblishTime));//成立时间
    $('#creditCode').text(empty2MinusSign(data.creditCode));//组织机构代码
    $('#category').text(empty2MinusSign(data.category));//国标行业门类
    $('#regLocation').text(empty2MinusSign(data.regLocation));//注册地址
    $('#regCapital').text(empty2MinusSign(data.regCapital));//注册资本
    $('#actualCapital').text(empty2MinusSign(data.actualCapital));//实缴资本
    $('#companyOrgType').text(empty2MinusSign(data.companyOrgType));//企业类型
    $('#regStatus').text(empty2MinusSign(data.regStatus));//登记状态
    $('#websiteList').text(empty2MinusSign(data.websiteList));//网址
    $('#phoneNumber').text(empty2MinusSign(data.phoneNumber));//联系电话
    $('#email').text(empty2MinusSign(data.email));
    
    
    $('#companyName').text(empty2MinusSign(data.name));
    $('#creditCode2').text(empty2MinusSign(data.creditCode));

    let scales = handleData('scales', data.scales);
    $('#scales').text(empty2MinusSign(scales));

    showTags(data.tags);
    $('#company-info-card').show();


    $('#companyNameList').empty().hide();
	    var creditCode2=data.creditCode;
	    var cname=data.name;
        getCompanyBaseInfoTable(data);
	    getCustomerAnalysisTableData(creditCode2);
	    getShareholderTableData(cname);
	    getCompanyChangeTable(cname);
	    getCompanyAptitudeTable(creditCode2);
	    getCompanyRecordTable(cname);
	    getCompanyCopyrightTable(cname);
	    getCompanyWorkrightTable(cname);
	    getCustomerAnalysisTable(cname);
	    getProductTable(creditCode2);
	    getCustomerInvestTable(creditCode2);
	    getFinancingTable(cname);
	    getcompetitorTable(cname);
	    getInvestInfoTable(cname);
}


function showTags(tags) {
    $('#company-tags').empty();
    if (typeof tags === 'string') {
        tags = tags.split(';');
    }
    $.each(tags, function (index, value) {
        let shadeClass = shades[index % shades.length];
        let span = $(`<span class="badge rounded-pill"></span>`);
        span.addClass(shadeClass);
        span.text(value);
        $('#company-tags').append(span);
    });
}


function addCompanyAccordion(data) {
    $('#companyNameList').empty().show();
    $.each(data, function (i, v) {
        let listItem = '<li class="list-group-item"><button onclick="searchCompanyInfo(\'' + v.creditCode + '\')" class="accordion-button collapsed" type="button">' + v.name + '</button></li>'
        $('#companyNameList').append(listItem);
    });

}

function keyMoreThan2(){
    let isComposing = false; // 标记是否正在输入法输入

    $('#search-data')
        .on('compositionstart', function () {
            isComposing = true;
        })
        .on('compositionend', function () {
            isComposing = false;
            triggerRequest();
        })
        .on('input', function () {
            if (!isComposing) {
                triggerRequest();
            }
        });
}

function triggerRequest() {
    const value = $('#search-data').val();
    if (value.length >= 2) {
        searchCompanyList()
    }
}

function hoard(){
    let creditCode = $('#creditCode').text();
    $.get(hoardURL+"?creditCode="+creditCode+"&hoard=1",function (result){
        alert('收藏成功');
    });
}

function getCompanyBaseInfoTable(companyData) {
    if (companyData) {
        $('#reportDataTime').empty().text(getNowDateTime());
        $('#companyNameTitle').empty().html(companyData.name);
        $('#competencyNameList').html('');
        let competencys = companyData.competencys?companyData.competencys.split('|'):'';
        if (($.trim(competencys) != '')) {
            $.each(competencys, function (i, d) {
                $('#competencyNameList').append("<li>" + d + "</li>");
            })
        }
        //企业名称
        $('#companyBaseInfoTableName').empty().html(companyData.name);
        //曾用名
        $('#companyBaseInfoTableHistoryNames').empty().text(companyData.historyName);
        //统一社会信用代码
        $('#companyBaseInfoTableCreditCode').empty().text(companyData.creditCode);
        //国标行业
        $('#companyBaseInfoTableCategory').empty().text(companyData.category);
        //纳税人识别号
        $('#companyBaseInfoTableTaxNumber').empty().text(companyData.taxNumber);
        //法定代表人
        $('#companyBaseInfoTableLegalPersonName').empty().text(companyData.legalPersonName);
        //联系方式
        $('#companyBaseInfoTablePhoneNumber').empty().text(companyData.phoneNumber);
        //注册资本
        $('#companyBaseInfoTableRegCapital').empty().text(companyData.regCapital);
        //实缴资本
        $('#companyBaseInfoTableActualCapital').empty().text(companyData.actualCapital);
        // 经营范围
        $('#companyBaseInfoTableBusinessScope').empty().text(companyData.businessScope);
    }
}

// 客户信息
function getCustomerAnalysisTableData(creditCode) {
    url = "https://test.zgcici.com/ep-api/api/park/portrait/tab/manage/client?unifiedCode=" + creditCode;
    $('#customerAnalysisTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows && result.rows.length > 0) {
            $.each(result.rows, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td>" + data.name + "</td>"))
                    .append($("<td>" + data.amount + "</td>"))
                    .append($("<td>" + data.ratio + "</td>"))
                    .append($("<td>" + data.sources + "</td>"))
                $('#customerAnalysisTable tbody').append($tr);
                $('#customerAnalysisTable').show();
            });
        } else {
            // $('#customerAnalysisTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#customerAnalysisTable').hide();
        }
    });
}

//股东信息
function getShareholderTableData(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=1&keyword=" + keyword;
    $('#shareholderTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td>" + data.name + "</td>"))
                    .append($("<td>" + data.subRate + "</td>"))
                    .append($("<td>" + data.subMoney + "</td>"))
                    .append($("<td>" + data.paidinMoney + "</td>"));
                $('#shareholderTable tbody').append($tr);
                $('#shareholderTable').show();
            });
        } else {
            // $('#shareholderTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#shareholderTable').hide();
        }
    });
}

//企业变更信息
function getCompanyChangeTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=2&keyword=" + keyword;
    $('#companyChangeTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.date + "</td>"))
                    .append($("<td class='truncate' title='" + data.oldValue + "'>" + data.oldValue + "</td>"))
                    .append($("<td class='truncate' title='" + data.newValue + "'>" + data.newValue + "</td>"));
                $('#companyChangeTable tbody').append($tr);
                $('#companyChangeTable').show();
            });
        } else {
            // $('#companyChangeTable tbody').append($("<tr><td colspan='3' align='center'>暂无数据</td></tr>"));
            $('#companyChangeTable').hide();
        }
    });
}

// 企业资质
function getCompanyAptitudeTable(creditCode) {
    url = 'https://test.zgcici.com/ep-api/api/park/portrait/tab/honor/aptitude?unifiedCode=' + creditCode + "&type=1";
    $('#companyAptitudeTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows && result.rows.length > 0) {
            $.each(result.rows, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.aptitude + "</td>"))
                    .append($("<td nowrap>" + data.level + "</td>"))
                    .append($("<td nowrap>" + data.unit + "</td>"))
                    .append($("<td nowrap>" + data.date + "</td>"));
                $('#companyAptitudeTable tbody').append($tr);
                $('#companyAptitudeTable').show();
            });
        } else {
            // $('#companyAptitudeTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#companyAptitudeTable').hide();
        }
    });
}

//备案许可
function getCompanyRecordTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=3&keyword=" + keyword;
    $('#companyRecordTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.name + "</td>"))
                    .append($("<td nowrap>" + data.no + "</td>"))
                    .append($("<td nowrap>" + data.date + "</td>"))
                    .append($("<td >" + data.unit + "</td>"));
                $('#companyRecordTable tbody').append($tr);
                $('#companyRecordTable').show();
            });
        } else {
            // $('#companyRecordTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#companyRecordTable').hide();
        }
    });
}

// 软件著作权
function getCompanyCopyrightTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=4&keyword=" + keyword;
    $('#companyCopyrightTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.name + "</td>"))
                    .append($("<td nowrap>" + data.abbreviation + "</td>"))
                    .append($("<td nowrap>" + data.versionNumber + "</td>"))
                    .append($("<td >" + data.copyrightOwner + "</td>"));
                $('#companyCopyrightTable tbody').append($tr);
                $('#companyCopyrightTable').show();
            });
        } else {
            // $('#companyCopyrightTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#companyCopyrightTable').hide();
        }
    });
}

// 作品著作权
function getCompanyWorkrightTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=5&keyword=" + keyword;
    $('#companyWorkrightTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.name + "</td>"))
                    .append($("<td nowrap>" + data.no + "</td>"))
                    .append($("<td nowrap>" + data.date + "</td>"))
                    .append($("<td >" + data.type + "</td>"));
                $('#companyWorkrightTable tbody').append($tr);
                $('#companyWorkrightTable').show();
            });
        } else {
            // $('#companyWorkrightTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#companyWorkrightTable').hide();
        }
    });
}

//客户分析
function getCustomerAnalysisTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=6&keyword=" + keyword;
    $('#customerAnalyticsTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.name + "</td>"))
                    .append($("<td nowrap>" + data.amount + "</td>"))
                    .append($("<td nowrap>" + data.ratio + "</td>"))
                    .append($("<td >" + data.sources + "</td>"));
                $('#customerAnalyticsTable tbody').append($tr);
                $('#customerAnalyticsTable').show();
            });
        } else {
            // $('#customerAnalyticsTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#customerAnalyticsTable').hide();
        }
    });
}

//产品分析
function getProductTable(creditCode) {
    url = 'https://test.zgcici.com/ep-api/api/park/portrait/tab/progress/product?unifiedCode=' + creditCode + "&type=1";
    $('#productTable tbody').empty();
    $.get(url, function (result) {
        if (result.rows && result.rows.length > 0) {
            $.each(result.rows, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.name + "</td>"))
                    .append($("<td nowrap>" + data.rounds + "</td>"))
                    .append($("<td nowrap>" + data.labe + "</td>"))
                    .append($("<td >" + data.local + "</td>"))
                    .append($("<td >" + data.introduction + "</td>"));
                $('#productTable tbody').append($tr);
                $('#productTable').show();
            });
        } else {
            // $('#productTable tbody').append($("<tr><td colspan='5' align='center'>暂无数据</td></tr>"));
            $('#productTable').hide();
        }
    });
}

//竞品分析
function getcompetitorTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=8&keyword=" + keyword;
    $('#competitorTable tbody').empty();
    $.get(url, function (result) {
        console.log(result);
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.name + "</td>"))
                    .append($("<td nowrap>" + data.rounds + "</td>"))
                    .append($("<td nowrap>" + data.labe + "</td>"))
                    .append($("<td >" + data.local + "</td>"))
                    .append($("<td >" + data.introduction + "</td>"))
                    .append($("<td >" + data.companyName + "</td>"));
                $('#competitorTable tbody').append($tr);
                $('#competitorTable').show();
            });
        } else {
            // $('#competitorTable tbody').append($("<tr><td colspan='6' align='center'>暂无数据</td></tr>"));
            $('#competitorTable').hide();
        }
    });
}

//融资分析
function getFinancingTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=9&keyword=" + keyword;
    $('#financingTable tbody').empty();
    $.get(url, function (result) {
        console.log(result);
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.date + "</td>"))
                    .append($("<td nowrap>" + data.rounds + "</td>"))
                    .append($("<td nowrap>" + data.amount + "</td>"))
                    .append($("<td >" + data.ratio + "</td>"))
                    .append($("<td >" + data.investor + "</td>"));
                $('#financingTable tbody').append($tr);
                $('#financingTable').show();
            });
        } else {
            // $('#financingTable tbody').append($("<tr><td colspan='5' align='center'>暂无数据</td></tr>"));
            $('#financingTable').hide();
        }
    });
}

//投资分析
function getCustomerInvestTable(creditCode) {
    url = 'https://test.zgcici.com/ep-api/api/park/portrait/tab/progress/invest?unifiedCode=' + creditCode + "&type=1";
    $('#customerInvestTable tbody').empty();
    $.get(url, function (result) {
        console.log(result);
        if (result.rows && result.rows.length > 0) {
            $.each(result.rows, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.entName + "</td>"))
                    .append($("<td nowrap>" + data.legalPerson + "</td>"))
                    .append($("<td nowrap>" + data.startDate + "</td>"))
                    .append($("<td >" + data.regRate + "</td>"))
                    .append($("<td >" + data.regCapital + "</td>"));
                $('#customerInvestTable tbody').append($tr);
                $('#customerInvestTable').show();
            });
        } else {
            // $('#customerInvestTable tbody').append($("<tr><td colspan='5' align='center'>暂无数据</td></tr>"));
            $('#customerInvestTable').hide();
        }
    });
}

//对外投资情况
function getInvestInfoTable(keyword) {
    url = getServiceHostAndPort() +"/api/v3/enterprise/search/tycQueryGdInfo?type=10&keyword=" + keyword;
    $('#investInfoTable tbody').empty();
    $.get(url, function (result) {
        console.log(result);
        if (result.rows.data && result.rows.data.length > 0) {
            $.each(result.rows.data, function (i, data) {
                let $tr = $("<tr></tr>")
                    .append($("<td nowrap>" + data.entName + "</td>"))
                    .append($("<td nowrap>" + data.startDate + "</td>"))
                    .append($("<td nowrap>" + data.regAddr + "</td>"))
                    .append($("<td >" + data.regRate + "</td>"));
                $('#investInfoTable tbody').append($tr);
                $('#investInfoTable').show();
            });
        } else {
            // $('#investInfoTable tbody').append($("<tr><td colspan='4' align='center'>暂无数据</td></tr>"));
            $('#investInfoTable').hide();
        }
    });
}


function getNowDateTime(){
    let now = new Date();
    var year = now.getFullYear(); // 年
    var month = now.getMonth() + 1; // 月 (月份从0开始，需要+1)
    var date = now.getDate(); // 日
    var hours = now.getHours(); // 小时
    var minutes = now.getMinutes(); // 分钟
    return`${year}-${month}-${date} ${hours}:${minutes}`;
}

function getQueryParam(name) {
    var regex = new RegExp("[?&]" + name + "=([^&#]*)", "i");
    var result = regex.exec(window.location.search);
    return result ? decodeURIComponent(result[1]) : null;
}